package com.ccl.iot.huiju;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;

import com.ccl.iot.App;
import com.ccl.iot.IOTInterface;
import com.ccl.iot.IOTInterface.IOTListMonitorInterface.IOTListChangeListener;
import com.ccl.iot.IOTNetAPIConst;
import com.ccl.iot.IOTObject;
import com.ccl.iot.IOTObject.IOTScannableObject.IOTScanListener;
import com.ccl.iot.R;
import com.ccl.iot.batch.BatchDBManager;
import com.ccl.iot.batch.IOTBatch;
import com.ccl.iot.bean.IOTBatchItemInfoBean;
import com.ccl.iot.device.IOTComplexDevice;
import com.ccl.iot.device.IOTDevice;
import com.ccl.iot.device.IOTVirtualDevice;
import com.ccl.iot.dvr.eventbus.PwdEvent;
import com.ccl.iot.dvr.utils.EventBusUtils;
import com.ccl.iot.dvr.utils.LogUtil;
import com.ccl.iot.dvr.utils.ToastUtil;
import com.ccl.iot.huiju.EditItemFragment.OnEditItemFragmentListener;
import com.ccl.iot.huiju.MainFragment.MainFragmentListener;
import com.ccl.iot.huiju.PositionItemFragment.OnPositionFragmentListener;
import com.ccl.iot.managers.BatchManager;
import com.ccl.iot.managers.DeviceManager;
import com.ccl.iot.managers.DeviceManager.OnScanDoneRefresh;
import com.ccl.iot.managers.MainManager;
import com.ccl.iot.managers.UserManager;
import com.ccl.iot.managers.UserManager.UserEventListener;
import com.ccl.iot.object.IOTBatchItemInfo;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;
import com.ccl.iot.template.StandardActivity;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class MainActivity extends StandardActivity implements OnEditItemFragmentListener, OnPositionFragmentListener, MainFragmentListener {


    //-------------------------------UI-------------

    private FragmentManager mFragmentManager;
    private FrameLayout mFragmentLayout;
    private BaseFragment mCurrentFragment;
    private MessageDialogFragment mMessageDialogFragment;


    //-------------------------------Data-----------

    public final static String TAG = "MainActivityO";

    private static final int HIDE_MASK = 9;

    private static final int REFRESH_EDIT_UI = 1;

    private static final int REFRESH_POSITION_UI = 2;

    private static final int REFRESH_MAIN_UI = 3;

    private static final int REFRESH_MAIN_UI_NO_LOGIN = 4;

    private BatchManager mBatchManager;
    private UserManager mUserManager;
    private MainManager mMainManager;
    private DeviceManager mDeviceManager;

    private ArrayList<IOTDevice> mDeviceList;

    private ArrayList<IOTHuiJu> mIOTHuiJuList;

    private IOTHuiJu mIOTHuiJu;

    private int mEditPageIndex;

    private boolean isLogon;
    private ArrayList<IOTBatch> mBatchList;


    @Override
    public void onEditPositionSelected(IOTHuiJu iotHuiJu, int page, int position) {
        LogUtil.e(TAG, "page:" + page + "--position:" + position);
        mIOTHuiJu = iotHuiJu;
        mEditPageIndex = page;

        PositionItemFragment positionItemFragment = new PositionItemFragment();
        switchFragment(positionItemFragment);

        mHandler.sendEmptyMessageDelayed(REFRESH_POSITION_UI, 100);

    }

    @Override
    public void onEditItemFragmentDestroy() {

        switchMainFragment();

    }

    @Override
    public void onEditRemoveIOTHuiJu(IOTHuiJu iotHuiJu) {
        showRemoveDialog(iotHuiJu);
    }


    public void showRemoveDialog(final IOTHuiJu iotHuiJu) {
        String message = App.getContext().getResources().getString(R.string.deleteItem_from_main);
        String name = null;

        if (iotHuiJu instanceof IOTDevice) {
            final IOTDevice device = (IOTDevice) iotHuiJu;
            name = device.getName();

        } else if (iotHuiJu instanceof IOTBatch) {
            final IOTBatch iotBatch = (IOTBatch) iotHuiJu;
            name = iotBatch.getName();
        }

        message = String.format(message, name);

        if (mMessageDialogFragment != null) {
            mMessageDialogFragment.dismiss();
        }

        mMessageDialogFragment = MessageDialogFragment.newInstance();
        mMessageDialogFragment.setMessage(message, new MessageDialogFragment.OnOKClickListener() {
            @Override
            public void onOKEvent() {
                if (mCurrentFragment instanceof EditItemFragment) {
                    EditItemFragment editItemFragment = (EditItemFragment) mCurrentFragment;
                    editItemFragment.getAdapter().deleteIOTHuiJu(iotHuiJu);
                }
            }
        });
        mMessageDialogFragment.show(getSupportFragmentManager(), "MessageDialogFragment");
    }

    public void switchMainFragment() {

        UIUtils.postTaskSafely(new Runnable() {
            @Override
            public void run() {
                MainFragment mainFragment = new MainFragment();
                switchFragment(mainFragment);
                mHandler.sendEmptyMessageDelayed(REFRESH_MAIN_UI, 100);
            }
        });

    }

    public void showNoLoginErrorLayout() {

        UIUtils.postTaskSafely(new Runnable() {
            @Override
            public void run() {
                MainFragment mainFragment = new MainFragment();
                switchFragment(mainFragment);

                mHandler.sendEmptyMessageDelayed(REFRESH_MAIN_UI_NO_LOGIN, 100);
            }
        });

    }

    @Override
    public void onPositionFragmentDestroy(int page) {
        LogUtil.e(TAG, "onSelectItemFragmentDestroy:");
        mEditPageIndex = page;
        EditItemFragment editItemFragment = new EditItemFragment();
        switchFragment(editItemFragment);
        mHandler.sendEmptyMessageDelayed(REFRESH_EDIT_UI, 100);

    }

    @Override
    public void goToEditFrag() {
        mEditPageIndex = 0;
        EditItemFragment editItemFragment = new EditItemFragment();
        switchFragment(editItemFragment);
        mHandler.sendEmptyMessageDelayed(REFRESH_EDIT_UI, 100);

        if (isLogon){
            downLoadBatchData();
        }

    }

    @Override
    public void reScanDevice() {
        mIOTHuiJuList.clear();
        startScan();
    }


    private static class MainHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        public MainHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();

            if (activity != null) {

                switch (msg.what) {

                    case REFRESH_EDIT_UI:
                        activity.refreshEditItemFragment();
                        break;

                    case REFRESH_POSITION_UI:
                        activity.refreshPositionItemFragment();
                        break;

                    case REFRESH_MAIN_UI:
                        activity.refreshMainFragment();
                        LogUtil.i(TAG, "activity.refreshMainFragment");
                        break;

                    case REFRESH_MAIN_UI_NO_LOGIN:
                        activity.refreshNoLoginUI();
                        LogUtil.i(TAG, "activity.showErrorLayout");
                        break;

                    case HIDE_MASK:
//                        activity.hideDeviceMaskLayout();
                        break;

                    default:

                        break;
                }
            }
        }
    }

    private final MainHandler mHandler = new MainHandler(this);


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //        LoggerUtil.e("onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        //        LoggerUtil.e("onRestoreInstanceState");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        EventBusUtils.register(this);

        initView();

        initListener();

        initData();

        switchFragment();

        hideBottomUIMenu();


//        CommonUtils.getMetrics(App.getContext());
//
//        float density = getResources().getDisplayMetrics().density;
//       LogUtil.i(TAG,"设备密度:" + density);

    }


    private void initView() {

        mFragmentLayout = (FrameLayout) findViewById(R.id.main_container);

    }


    private void initListener() {


        View decorView = getWindow().getDecorView();
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener()

                {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        // Note that system bars will only be "visible" if none of the
                        // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            // TODO: The system bars are visible. Make any desired
                            // adjustments to your UI, such as showing the action bar or
                            // other navigational controls.
                            hideBottomUIMenu();
                        } else {
                            // TODO: The system bars are NOT visible. Make any desired
                            // adjustments to your UI, such as hiding the action bar or
                            // other navigational controls.
                        }
                    }
                });

    }

    private void initData() {
        mBatchManager = BatchManager.GetDefaultManager();
        mUserManager = UserManager.GetDefaultManager();
        mMainManager = MainManager.GetDefaultManager();
        mDeviceManager = DeviceManager.GetDefaultManager();

        if (mUserManager != null) {
            mUserManager.addUserEventListener(mUserEventListener);
            long logonUser = mUserManager.getLogonUser();
            if (logonUser != IOTNetAPIConst.KINVALID_USER_ID) {
                File file = new File(MainManager.KDEFAULT_DATABASE_PATH + "geo/" + logonUser);
                if (file != null && file.exists() && file.isDirectory()) {
                    String[] list = file.list();
                    if (list != null && list.length > 0) {
                    }
                }
            }
        }

        mDeviceList = new ArrayList<>();
        mIOTHuiJuList = new ArrayList<>();

    }




    public void switchFragment() {

        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mCurrentFragment = new MainFragment();

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_container, mCurrentFragment, "MainFragment");
        fragmentTransaction.commit();

    }


    public void switchFragment(BaseFragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

        fragmentTransaction.replace(R.id.main_container, fragment).commit();

        mCurrentFragment = fragment;
    }


    /**
     * 设置登录按钮图片
     */
    public boolean isLogin() {
        if (mUserManager != null){
            isLogon = mUserManager.isLogon();
        }else {
            isLogon = false;
        }

        return isLogon;
    }

    /*
     * Update part
     */


    @Override
    protected void onResume() {
        super.onResume();

        isLogin();

        startScan();

    }

    public void startScan() {

        isLogin();

        if (mBatchManager != null) {

            mBatchManager.setOnListChangeListener(mBatchsListener);

            if (isLogon){
                ThreadPoolUtils.getInstance().addTask(new Runnable() {

                    @Override
                    public void run() {
                        mBatchManager.startScan(mBatchScanListener);
                    }
                });
            }else {

                addBatch2List();
                refreshMainFragmentMsg();

            }


        }


        if (mDeviceManager != null) {
            //添加刷新完成的回调
            mDeviceManager.removeScanDoneRefreshListener(mDeviceScanDoneListener);
            mDeviceManager.addScanDoneRefreshListener(mDeviceScanDoneListener);

            ThreadPoolUtils.getInstance().addTask(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 2; i++) {
                        mDeviceManager.startScan(null, true);
                    }
                }
            });

        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mDeviceManager != null) {
            mDeviceManager.removeScanDoneRefreshListener(mDeviceScanDoneListener);
        }

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        EventBusUtils.unregister(this);


        if (mUserManager != null) {
            mUserManager.removeUserEventListener(mUserEventListener);
        }

        mHandler.removeCallbacksAndMessages(null);
    }


    /**
     * 设置安防密码
     *
     * @param event
     */
    @Subscribe
    public void onPwdEvent(PwdEvent event) {

    }


    public void logoutUser() {
        showLogoutDialog();
    }


    public void logout() {
        if (mUserManager != null && mUserManager.isLogon()) {
            if (!mUserManager.logout()) {
                ToastUtil.showLongToastCenter(App.getContext().getString(R.string.Error_LogoutFailed));
            }
        }
    }


    /**
     * 注销对话框
     */
    public void showLogoutDialog() {

        String message = App.getContext().getResources().getString(R.string.logout_msg);

        if (mMessageDialogFragment != null) {
            mMessageDialogFragment.dismiss();
        }

        mMessageDialogFragment = MessageDialogFragment.newInstance();
        mMessageDialogFragment.setMessage(message, new MessageDialogFragment.OnOKClickListener() {
            @Override
            public void onOKEvent() {
                logout();
            }
        });
        mMessageDialogFragment.show(getSupportFragmentManager(), "MessageDialogFragment");


    }


    private void initDeviceList(ArrayList<IOTDevice> deviceList) {
        if (deviceList != null) {

            LogUtil.i(TAG, "initDeviceList");

            if (mDeviceList != null) {

                mDeviceList.clear();

                if (isLogon){
                    //过滤无权限的设备
                    Iterator<IOTDevice> iterator = deviceList.iterator();
                    while (iterator.hasNext()) {
                        IOTDevice device = iterator.next();
                        if (device != null) {
                            if (!device.isReadable() && !device.isWritable()) {
                                iterator.remove();
                            }
                        }
                    }
                }


                int index = 0;
                //分解多路设备
                for (IOTDevice dev : deviceList) {
                    if (dev != null) {
                        if (dev instanceof IOTComplexDevice) {
                            IOTComplexDevice iotComplexDevice = (IOTComplexDevice) dev;
                            int count = iotComplexDevice.getDeviceCount();
                            for (int i = 0; i < count; i++) {
                                IOTDevice device = iotComplexDevice.getDevice(i);
                                if (device != null) {
                                    boolean add = !device.isHide() && device.isOnline() && !mDeviceList.contains(device);
                                    if (add) {
                                        mDeviceList.add(index, device);
                                        index++;
                                    }
                                }

                            }
                        } else {
                            boolean add = !dev.isHide() && dev.isOnline() && !mDeviceList.contains(dev);
                            if (add) {
                                if (dev instanceof IOTVirtualDevice) {
                                    mDeviceList.add(dev);
                                } else {
                                    mDeviceList.add(index, dev);
                                    index++;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public void addDevice2List() {

        refreshDeviceList();

        if (mDeviceList != null) {
            int size = mDeviceList.size();
            for (int i = 0; i < size; i++) {
                IOTDevice iotDevice = mDeviceList.get(i);
                String simpleName = iotDevice.getClass().getSimpleName();
                if (!simpleName.equals("IOTMultiFunc5525") && !mIOTHuiJuList.contains(iotDevice)) {
                    mIOTHuiJuList.add(iotDevice);
                    LogUtil.i(TAG, "IOTDevice:" + iotDevice.getName() + "---index:" + mIOTHuiJuList.indexOf(iotDevice));
                }
            }
        }

    }

    private int reStartCount;

    public void addBatch2List() {
        if (mBatchManager != null) {
            if (isLogon){
                mBatchList = mBatchManager.getList();
                if (mBatchList == null) {
                    mBatchList = mBatchManager.getList();
                }
            }else {
                mBatchList  = mBatchManager.getOfflineData();
            }

            if (mBatchList != null) {
                int size = mBatchList.size();
                for (int i = 0; i < size; i++) {
                    IOTBatch iotBatch = mBatchList.get(i);
                    if (!mIOTHuiJuList.contains(iotBatch)) {
                        mIOTHuiJuList.add(iotBatch);
                        LogUtil.i(TAG, "IOTBatch:" + iotBatch.getName() +"--id:" + iotBatch.getID()
                                + "--index:" + mIOTHuiJuList.indexOf(iotBatch));
                    }
                }
            } else {
                if (reStartCount < 10) {
                    ThreadPoolUtils.getInstance().addTask(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                                mBatchManager.startScan(mBatchScanListener);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    reStartCount++;
                }
            }
        }
    }

    public ArrayList<IOTHuiJu> getIOTHuiJuList() {
        return mIOTHuiJuList;
    }

    /**
     * 当设备变化时刷新界面
     */
    public void refreshDeviceList() {

        if (mDeviceManager != null) {
            initDeviceList(mDeviceManager.getList(true));
        }

    }

    public void refreshEditItemFragment() {

        if (mCurrentFragment instanceof EditItemFragment) {
            ((EditItemFragment) mCurrentFragment).refreshUI(mIOTHuiJuList, mEditPageIndex);
        }


    }

    public void refreshPositionItemFragment() {

        if (mCurrentFragment instanceof PositionItemFragment) {
            ((PositionItemFragment) mCurrentFragment).setItemData(mIOTHuiJu, mEditPageIndex);
        }

    }

    public void refreshMainFragment() {

        if (mCurrentFragment instanceof MainFragment) {
            ((MainFragment) mCurrentFragment).refreshUI(mIOTHuiJuList);
            LogUtil.e(MainFragment.TAG, "refreshUI----");
        }

    }

    public void refreshNoLoginUI() {

        if (mCurrentFragment instanceof MainFragment) {
            ((MainFragment) mCurrentFragment).showNoLoginErrorLayou();
            LogUtil.e(MainFragment.TAG, "showNoLoginErrorLayou----");
        }

    }

    public void refreshMainFragmentMsg() {

        if (mHandler != null) {
            if (mHandler.hasMessages(REFRESH_MAIN_UI)) {
                mHandler.removeMessages(REFRESH_MAIN_UI);
            }
            mHandler.sendEmptyMessageDelayed(REFRESH_MAIN_UI, 1500);
        }

    }

    //---------------------------------回调------------------------


    private UserEventListener mUserEventListener = new UserEventListener() {
        @Override
        public void onLoginEvent(boolean aCanceled) {

            isLogin();

            startScan();
            switchMainFragment();

            LogUtil.e(TAG, "-------------onLoginEvent：" + isLogon);
        }

        @Override
        public void onPrepareLogout() {
        }

        @Override
        public void onLogout(boolean aOK) {
            mIOTHuiJuList.clear();
            LogUtil.e(TAG, "-------------onLogout");
        }
    };

    private IOTListChangeListener<IOTBatch> mBatchsListener = new IOTListChangeListener<IOTBatch>() {

        /**
         * 当有新的批处理条目加入
         * @param aSource
         * @param aObject
         */
        @Override
        public void onNewObject(IOTInterface.IOTListMonitorInterface<IOTBatch> aSource, IOTBatch aObject) {
        }

        /**
         * 当有批处理条目删除
         * @param aSource
         * @param aObject
         */
        @Override
        public void onObjectRemoved(IOTInterface.IOTListMonitorInterface<IOTBatch> aSource, IOTBatch aObject) {
        }
    };


    /**
     * 批处理扫描的监听器
     */
    private IOTScanListener<IOTBatch> mBatchScanListener = new IOTScanListener<IOTBatch>() {

        /**
         * 批处理扫描结束
         */
        @Override
        public void onScanStop(IOTObject.IOTScannableObject<?> aScanner) {

            LogUtil.e(TAG, "mBatchScanListener--onScanStop");

            addBatch2List();

            refreshMainFragmentMsg();

        }

        /**
         * 批处理扫描开始
         */
        @Override
        public void onScanStart(IOTObject.IOTScannableObject<?> aScanner) {

        }

        /**
         * 批处理扫描结果(单次)
         * @param aScanner
         * @param aObject
         */
        @Override
        public void onScanResult(IOTObject.IOTScannableObject<?> aScanner, IOTBatch aObject) {

        }
    };


    private OnScanDoneRefresh mDeviceScanDoneListener = new OnScanDoneRefresh() {
        @Override
        public void onRefresh(IOTDevice newDev) {
            synchronized (mDeviceList.getClass()) {

                LogUtil.e(TAG, "mDeviceScanDoneListener--onRefresh");

                addDevice2List();

                refreshMainFragmentMsg();
            }

        }
    };

    /**
     * 隐藏虚拟按键，并且全屏
     */
    public void hideBottomUIMenu() {

        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

    }

    public void downLoadBatchData(){

        ThreadPoolUtils.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                if (mBatchManager != null) {
                    ArrayList<IOTBatch>  mBatchList = mBatchManager.getList();
                    if (mBatchList != null){

                        int size = mBatchList.size();
                        for (int i = 0; i < size; i++) {
                            IOTBatch iotBatch = mBatchList.get(i);
                            long iotBatchID = iotBatch.getID();
                            ArrayList<IOTBatchItemInfo> batchItemInfo = mBatchManager.getAllBatchItemInfo(iotBatchID);

                            if (batchItemInfo != null){
                                int batchItemInfoSize = batchItemInfo.size();

                                List<IOTBatchItemInfoBean> IOTBatchItemInfoBeanList = new ArrayList<IOTBatchItemInfoBean>();

                                for (int j = 0; j < batchItemInfoSize; j++) {
                                    IOTBatchItemInfo iotBatchItemInfo = batchItemInfo.get(j);
                                    long iID = iotBatchItemInfo.iID;
                                    long iDevID = iotBatchItemInfo.iDevID;
                                    int iAddress = iotBatchItemInfo.iAddress;
                                    int iSize = iotBatchItemInfo.iSize;
                                    byte[] iData = iotBatchItemInfo.iData;

                                    IOTBatchItemInfoBean iotBatchItemInfoBean = new IOTBatchItemInfoBean();
                                    iotBatchItemInfoBean.setiID(iID);
                                    iotBatchItemInfoBean.setiDevID(iDevID);
                                    iotBatchItemInfoBean.setiAddress(iAddress);
                                    iotBatchItemInfoBean.setiSize(iSize);
                                    iotBatchItemInfoBean.setiData(iData);

                                    if (!IOTBatchItemInfoBeanList.contains(iotBatchItemInfoBean)){
                                        IOTBatchItemInfoBeanList.add(iotBatchItemInfoBean);
                                    }
                                }

                                try {
                                    Gson gson = new Gson();
                                    String batchItemInfoJson = gson.toJson(IOTBatchItemInfoBeanList);
                                    LogUtil.i(TAG,"batchItemInfoJson：" + batchItemInfoJson);
                                    BatchDBManager.saveBatch(iotBatchID,iotBatch.getNameAndImgIndex(),batchItemInfoJson);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        }
                        LogUtil.e(TAG,"----下载完成" );
                    }
                }
            }
        });
    }




}
